package com.zhiyou.app.shop.website.util;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * @author 
 * 
 */

public class SpringBeanFactory {
	
	private static Log _log=LogFactory.getLog(SpringBeanFactory.class);
	
	private static ApplicationContext springContext;

	private static ServletContext servletContext;

	private static final String[] contextPath = {"spring/datasource-config.xml"};
	
	public static ServletContext getServletContext() {
		return servletContext;
	}

	public static void setServletContext(ServletContext servletContext) {
		SpringBeanFactory.servletContext = servletContext;
	}

	public static ApplicationContext getSpringContext() {
		if (servletContext != null) {
			springContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		} else {
			if(springContext==null){
				_log.error("Spring Web Container Is Running In Non Application Mode Please Confirm !");
				
				if("debug".equals("debug")){
					ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
					List list=new ArrayList();
					for (int i = 0; i < contextPath.length; i++) {
						contextPath[i]="classpath:"+contextPath[i].trim();
						try {
							resourcePatternResolver.getResources(contextPath[i]);
							list.add(contextPath[i]);
						} catch (Exception e) {
							_log.error(e.getMessage());
						}
						_log.info(contextPath[i]);
					}
					String[] loc=new String[list.size()];
					loc=(String[]) list.toArray(loc);
					springContext = new ClassPathXmlApplicationContext(loc);
				}else{
					new RuntimeException("Server Is Running In Run Mode Init Error !");
				}
			}
			

		}
		return springContext;
	}

	public static Object getBean(String beanName) {
		return getSpringContext().getBean(beanName);
	}
}
